<?php
/**
 * Created by PhpStorm.
 * User: zqijun
 * Date: 18-6-25
 * Time: 下午10:35
 */

namespace common\components\ActionsComponents;

use common\components\DataHelper;

class ListViewAction extends CommonAction
{
    public $view = "index";
    public $order = "id desc";
    public $fields = [];
    public $with;
    public $layout = false;
    public $pageSize = 30;
    public $params = [];
    public $isSetRelv = 0;
    public $isObject = false;

    public function run()
    {
        $controller = $this->controller;
        $model = new $this->model();
        $model->fields = $this->fields;
        $query = $model->getListAll($this->condition, true);

        if ( method_exists($model, "createSearchCondition") ) {
            $model->createSearchCondition($query, \Yii::$app->request->get());
        }

        $this->pageSize && $page = DataHelper::getPage($query->count(), $this->pageSize);

        if ( $this->order ) {
            $query->orderBy($this->order);
        }

        if ( $this->with ) {
            $query->with($this->with);
        }

        if ( $this->pageSize ) {
            $ret = !$this->isObject ? $query->offset($page->offset)->limit($page->limit)->asArray()->all() : $query->offset($page->offset)->limit($page->limit)->all();
        } else {
            $ret = !$this->isObject ? $query->asArray()->all() : $query->all();
        }

        if ( $this->layout ) {
            if ( $this->layout instanceof \Closure ) {
                $layout = $this->layout;
                $this->layout = $layout();

                if ( $this->layout && !is_string($this->layout) )  {
                    throw new \Exception('condition 参数必须是一个字符串');
                }
            }
            $this->layout && $controller->layout = $this->layout;
        }


        if ( $this->view instanceof \Closure ) {
            $view = $this->view;
            $this->view = $view();

            if ( !is_string($this->view) )  {
                throw new \Exception('condition 参数必须是一个字符串');
            }
        }

        if ( $this->params instanceof \Closure ) {
            $params = $this->params;
            $this->params = $params();

            if ( !is_array($this->params) )  {
                throw new \Exception('condition 参数必须是一个数组');
            }
        }

        $this->params = $this->params ? array_merge($this->params, [
            "ret" => $ret,
            "page" => isset($page) ? $page : ""
        ]) :  [
            "ret" => $ret,
            "page" => isset($page) ? $page : ""
        ];

        if ( $this->isSetRelv ) {
            $controller->setRelv();
        }
        return $controller->render($this->view, $this->params);
    }
}